﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Client.Forms
{
    public partial class LoginForm : Form
    {
        int gap = 10;
        int left = 35;

        List<Control> loginCs= new List<Control>();
        List<Control> registerCs = new List<Control>();
        List<Control> resetPasswdCs = new List<Control>();

        public LoginForm()
        {
            Managers.Manager.loginForm = this;

            InitializeComponent();
            loginCs.AddRange(new Control[] { userNamePanel, passwordPanel, loginButtonPanel });
            registerCs.AddRange(new Control[] { userNamePanel, nicknamePanel, passwordPanel, rePasswordPanel, yzmPanel, registerPanel, returnLink});
            resetPasswdCs.AddRange(new Control[] { userNamePanel, passwordPanel, rePasswordPanel, yzmPanel, commitPanel, returnLink});

            ChangeLoginPanel();

            
        }
        private void Login_FormClosed(object sender, FormClosedEventArgs e)
        {
            Managers.Manager.ExitApp();
        }




        private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            passwdTextBox.Text = "";
            userTextBox.AccessibleDescription = "请输入十一位中国大陆手机号";
            passwdTextBox.AccessibleName = "密码";
            SetUI(registerCs);
            this.AcceptButton = registerButton;
            this.Text = "新用户注册";
        }
        private void LinkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            passwdTextBox.Text = "";
            SetUI(resetPasswdCs);
            userTextBox.AccessibleDescription = "请输入已注册的手机号";
            passwdTextBox.AccessibleName = "新密码";
            this.AcceptButton = commitButton;
            this.Text = "重置密码";
        }
        private void ReturnLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ChangeLoginPanel();
        }
        private void LoginButton_Click(object sender, EventArgs e)
        {
            if (!IsPhone() || !IsPasswd())
                return;
            this.Enabled = false;
            Login(userTextBox.Text, passwdTextBox.Text);
        }
        private async void RegisterButton_Click(object sender, EventArgs e)
        {
            if (!IsPhone() || !IsPasswd())
                return;
            if (nicknameTextBox.Text == "")
            {
                MessageBox.Show("昵称不能为空。", "提示");
                nicknameTextBox.Focus();
                return;
            }
            if (passwdTextBox.Text != repasswdTextBox.Text)
            {
                MessageBox.Show("两次输入的密码不一致。", "提示");
                repasswdTextBox.Focus();
                return;
            }

            try
            {
                this.Enabled = false;
                await DataCenter.DataCenter.Register(userTextBox.Text, nicknameTextBox.Text, passwdTextBox.Text, yzmTextBox.Text);
                yzmTextBox.Text = "";
                repasswdTextBox.Text = "";
                Managers.Manager.settingM.generalSetting["user_id"] = userTextBox.Text;
                Managers.Manager.settingM.generalSetting["pwd"] = "";
                this.rememberPWDCheckBox.CheckState = CheckState.Unchecked;
                await Login(userTextBox.Text, passwdTextBox.Text);
            }
            catch (DataCenter.MyException.APIReturnException error)
            {
                CookException(error);
            }
        }
        private async void CommitButton_Click(object sender, EventArgs e)
        {
            if (!IsPhone() || !IsPasswd())
                return;
            if (passwdTextBox.Text != repasswdTextBox.Text)
            {
                MessageBox.Show("两次输入的密码不一致。", "提示");
                repasswdTextBox.Focus();
                return;
            }

            try
            {
                this.Enabled = false;
                await DataCenter.DataCenter.ResetPasswd(userTextBox.Text, passwdTextBox.Text, yzmTextBox.Text);
                yzmTextBox.Text = "";
                repasswdTextBox.Text = "";
                Managers.Manager.settingM.generalSetting["user_id"] = userTextBox.Text;
                Managers.Manager.settingM.generalSetting["pwd"] = "";
                this.rememberPWDCheckBox.CheckState = CheckState.Unchecked;
                MessageBox.Show("重置密码成功，即将登陆。", "提示");
                await Login(userTextBox.Text, passwdTextBox.Text);
            }
            catch (DataCenter.MyException.APIReturnException error)
            {
                CookException(error);
            }
        }



        private void ReturnLink_Move(object sender, EventArgs e)
        {
            returnLink.Location = new Point(3, 3);
        }

        void ChangeLoginPanel()
        {
            FillUser();
            userTextBox.AccessibleDescription = "请输入已注册的手机号";
            passwdTextBox.AccessibleName = "密码";
            SetUI(loginCs);
            loginButton.Enabled = true;
            this.AcceptButton = loginButton;
            this.Text = MyConst.StaticString.APPNAME + "用户登录";
            if (userTextBox.Text != "")
                passwdTextBox.Focus();
        }
        async Task<bool> Login(string userId, string passwd)
        {
            try
            {
                var str = await DataCenter.DataCenter.Login(userId, passwd);
                SaveUser();
                this.Hide();
                new Client().Show();
            }
            catch (DataCenter.MyException.APIReturnException e)
            {
                if (CookException(e, 2) == 2)
                {
                    SaveUser();
                    new TopUpForm(userId).Show();
                    this.Hide();
                }
                return false;
            }
            return true;
        }
        void SetUI(List<Control> l)
        {
            foreach (Control c in this.Controls)
            {
                c.Visible = false;
            }

            int h = 0;
            for (int i = 0; i < l.Count; i++)
            {
                h += l[i].Height;
                l[i].TabIndex = i;
            }
            h += (l.Count - 1) * gap;
            int start = (this.Height - h) / 2 - 20;

            h = 0;
            for (int i = 0; i < l.Count; i++)
            {

                l[i].Location = new Point(left, start + i * gap + h);
                h += l[i].Height;
                l[i].Visible = true;
            }

            userTextBox.Focus();
        }
        bool IsPhone()
        {
            string pattern = @"^1[345789]\d{9}$";
            
            if (!Regex.IsMatch(userTextBox.Text, pattern))
            {
                MessageBox.Show("用户名需填入已注册的手机号。", "用户名格式不正确");
                userTextBox.Focus();
                return false;
            }
            return true;
        }
        bool IsPasswd()
        {
            string pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
            
            if (!Regex.IsMatch(passwdTextBox.Text, pattern))
            {
                MessageBox.Show("密码必须由数字和字母组成，且长度要在 8 - 16 位之间。", "密码格式不正确");
                passwdTextBox.Focus();
                return false;
            }
            return true;
        }
        int CookException(Exception e, int expCode = 0)
        {
            this.Enabled = true;
            if (e.Message.IndexOf('~') != -1)
            {
                var msgs = e.Message.Split('~');
                int code = int.Parse(msgs[0]);
                if (code!=expCode)
                    MessageBox.Show(msgs[1], "提示");
                Console.WriteLine("errorCode:" + msgs[0] + "\nmsg：" + msgs[1]);
                userTextBox.Focus();
                return code;
            }
            MessageBox.Show(e.Message+"\n请联系管理员", "错误");
            return -1000;
        }
        void FillUser()
        {
            string uid = Managers.Manager.settingM.GetGeneralValue("user_id");
            userTextBox.Text = uid;
            string pwd = Managers.Manager.settingM.GetGeneralValue("pwd");
            if (pwd != "")
            {
                passwdTextBox.Text = pwd;
                rememberPWDCheckBox.CheckState = CheckState.Checked;
            }
        }
        void SaveUser()
        {
            if (rememberPWDCheckBox.CheckState == CheckState.Unchecked)
                passwdTextBox.Text = "";
            Managers.Manager.settingM.generalSetting["pwd"] = passwdTextBox.Text;
            Managers.Manager.settingM.generalSetting["user_id"] = userTextBox.Text;
        }

        private void LoginForm_VisibleChanged(object sender, EventArgs e)
        {
            this.Enabled = true;
            ChangeLoginPanel();
        }

        private async void GetYZMLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (IsPhone())
            {
                DataCenter.DataCenter.SendYZM(userTextBox.Text);
                getYZMLinkLabel.LinkClicked -= GetYZMLinkLabel_LinkClicked;
                string tmpText = getYZMLinkLabel.Text;
                string tmpAccName = getYZMLinkLabel.AccessibleName;
                yzmTextBox.Focus();
                for(int i = 60; i >0; i--)
                {
                    string str = i + "秒后重新获取";
                    getYZMLinkLabel.Text = str;
                    getYZMLinkLabel.AccessibleName = str;
                    await Task.Delay(1000);
                }
                getYZMLinkLabel.LinkClicked += GetYZMLinkLabel_LinkClicked;
                getYZMLinkLabel.Text = tmpText;
                getYZMLinkLabel.AccessibleName = tmpAccName;
            }
        }

        private void TextBoxSelectAll(object sender,EventArgs e)
        {
            var s = (TextBox)sender;
            s.SelectAll();
        }


        private void UserTextBox_TextChanged(object sender, EventArgs e)
        {
            passwdTextBox.Text = "";
            rememberPWDCheckBox.CheckState = CheckState.Unchecked;
            SpaceLimit(sender, e);
        }
        private void PasswdTextBox_TextChanged(object sender, EventArgs e)
        {
            rememberPWDCheckBox.CheckState = CheckState.Unchecked;
            SpaceLimit(sender, e);
        }

        void SpaceLimit(object sender, EventArgs e)
        {
            var s = (TextBox)sender;
            s.Text = System.Text.RegularExpressions.Regex.Replace(s.Text, @"\s", "");
            s.SelectionStart = s.Text.Length;
        }

        private void LoginForm_Shown(object sender, EventArgs e)
        {
            if (userTextBox.Text != "")
                passwdTextBox.Focus();
        }
    }
}
